package com.b2wx.appcenter.plugin;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.PreDestroy;

import com.b2wx.appcenter.util.common.JedisUtil;

public class SocketServer {
	private static boolean closed = true;
	private static String socketServer = null;
	private static String httpServer = null;
	private static ServerSocket serverSocket;

	public static void start() {
		Set<String> pluginIdSet = new HashSet<>();
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					socketServer = System.getProperty("socketServer");
					httpServer = System.getProperty("httpServer");
					serverSocket = new ServerSocket(Integer.parseInt(socketServer.split(":")[1]));
					closed = false;
					JedisUtil.build().doAfterClose(jedis->{
						jedis.hset("plugin.server", socketServer, "0");
						System.out.println(socketServer+"已经成功加入插件服务器列表");
					});
					
					while(!closed) {
						Socket socket = serverSocket.accept();
						if(closed) {
							break;
						}
						PluginClient pc = new PluginClient(socket);
						pc.addSocketListener(new PluginClient.SocketListener() {
							@Override
							public void onOpen(String pluginId, Map<String, Object> config) {
								if(!closed) {
									JedisUtil.build().doAfterClose(jedis->{
										jedis.hincrBy("plugin.server", socketServer, 1);
										jedis.hset("plugin.mapping", pc.getClientKey(),httpServer);
										pluginIdSet.add(pc.getClientKey());
									});
								}
							}
							@Override
							public void onClose(String pluginId, Map<String, Object> config) {
								if(!closed) {
									JedisUtil.build().doAfterClose(jedis->{
										jedis.hincrBy("plugin.server", socketServer, -1);
										jedis.hdel("plugin.mapping", pc.getClientKey());
										pluginIdSet.remove(pc.getClientKey());
									});
								}
							}
						});
						pc.start();
					}
					serverSocket.close();
				}catch (IOException e) {
					e.printStackTrace();
				}finally {
					JedisUtil.build().doAfterClose(jedis->{
						jedis.hdel("plugin.server",socketServer);
						if(!pluginIdSet.isEmpty()) {
							jedis.hdel("plugin.mapping", pluginIdSet.toArray(new String[pluginIdSet.size()]));
						}
					});
				}
			}
		}).start();
	}

	@PreDestroy
	public void destory() {
		System.out.println("注销插件服务器");
		SocketServer.close();
	}
	public static void close() {
		if (!closed) {
			closed = true;
			try {
				new Socket("localhost", serverSocket.getLocalPort()).close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
